package com.itheima.aop;

import com.itheima.dao.AccountDao;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

/**
 * @program: Spring_day01_01_IOC入门程序
 * @description: 通知
 * @author: xuejingjing
 * @create: 2021-08-08 00:44
 **/
public class TxAdvice {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Object transactionManager(ProceedingJoinPoint pjp) throws Throwable {

        //开启事务
        //1,先拿到平台事务管理器
        PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);
        //事务定义
        TransactionDefinition td = new DefaultTransactionDefinition();
        //事务状态
        TransactionStatus ts = ptm.getTransaction(td);
        Object ret = pjp.proceed(pjp.getArgs());

        /*具体的业务通知中不写
        accountDao.inMoney(outName,money);
        int i = 1/0;
        accountDao.outMoney(inName,money);
        */
        //提交事务
        ptm.commit(ts);
        return ts;
    }
}
